import type { Context } from 'elysia';
import { eq, count, desc } from 'drizzle-orm';
import { db } from '../db';
import { products, cases, users } from '../db/schema';
import { successResponse, errorResponse, ApiError, asyncHandler, Logger } from '../utils/response';

// 获取仪表盘统计数据
export const getDashboardStats = asyncHandler(async ({ }: Context) => {
  try {
    // 获取统计数据
    const [productStats, caseStats, userStats] = await Promise.all([
      // 产品统计
      db.select({ count: count() })
        .from(products),
      
      // 案例统计
      db.select({ count: count() })
        .from(cases)
        .where(eq(cases.status, 'active')),
      
      // 用户统计
      db.select({ count: count() })
        .from(users)
    ]);

    // 获取最近的产品和案例
    const [recentProducts, recentCases] = await Promise.all([
      db.select({
        id: products.id,
        name: products.name,
        type: products.type,
        createdAt: products.createdAt
      })
        .from(products)
        .orderBy(desc(products.createdAt))
        .limit(5),
      
      db.select({
        id: cases.id,
        title: cases.title,
        client: cases.clientName,
        industry: cases.industry,
        createdAt: cases.createdAt
      })
        .from(cases)
        .where(eq(cases.status, 'active'))
        .orderBy(desc(cases.createdAt))
        .limit(5)
    ]);

    // 真实的统计数据
    const stats = {
      totalProducts: productStats[0]?.count || 0,
      totalCases: caseStats[0]?.count || 0,
      totalUsers: userStats[0]?.count || 0,
      totalViews: 0, // 实际浏览量需要从数据库获取
      recentProducts,
      recentCases,
      systemStatus: {
        server: 'online',
        database: 'online',
        storage: 'online'
      },
      monthlyStats: {
        products: 0,
        cases: 0,
        views: 0
      }
    };

    Logger.info('Dashboard stats retrieved', { 
      totalProducts: stats.totalProducts, 
      totalCases: stats.totalCases, 
      totalUsers: stats.totalUsers 
    });
    return successResponse(stats);
  } catch (error) {
    Logger.error('Failed to get dashboard stats', { error: error.message });
    throw ApiError.internal('获取仪表盘统计数据失败');
  }
});

// 获取系统状态
export const getSystemStatus = asyncHandler(async ({ }: Context) => {
  // 检查数据库连接
  await db.select({ count: count() }).from(users).limit(1);
  
  const status = {
    server: {
      status: 'online',
      uptime: process.uptime(),
      memory: process.memoryUsage(),
      cpu: process.cpuUsage()
    },
    database: {
      status: 'online',
      connections: 1 // 实际连接数需要从数据库获取
    },
    storage: {
      status: 'online',
      used: 0, // 实际存储使用率需要从系统获取
      total: 100
    }
  };

  Logger.info('System status retrieved');
  return successResponse(status);
});

// 获取月度统计数据
export const getMonthlyStats = asyncHandler(async ({ }: Context) => {
  // 真实的月度统计数据
  const monthlyData = [];
  const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
  
  for (let i = 0; i < 12; i++) {
    monthlyData.push({
      month: months[i],
      products: 0, // 需要从数据库按月统计
      cases: 0, // 需要从数据库按月统计
      views: 0 // 需要从数据库按月统计
    });
  }
  
  Logger.info('Monthly stats retrieved');
  return successResponse(monthlyData);
});